/**
 * Created by xu on 2016/1/15.
 */

function inputOnlyNUM(e, obj)//添加keypress事件  只允许输入数字
{
    if(obj != null && $(obj).val().length >= 13) {	//长度不能超过9位
        return false;
    }
    var isie = (document.all) ? true : false;//判断是IE内核还是Mozilla
    var key;
    if(isie) {
        key = window.event.keyCode;//IE使用windows.event事件
    } else {
        key = e.which;//3个按键函数有一个默认的隐藏变量，这里用e来传递。e.which给出一个索引值给Mo内核（注释1）
    }
    if(key == 8) {
        return true;
    }
    return /[0-9]/.test(String.fromCharCode(key));
}

String.prototype.startWith=function(str){
    var reg=new RegExp("^"+str);
    return reg.test(this);
};

String.prototype.endWith=function(str){
    var reg=new RegExp(str+"$");
    return reg.test(this);
};


//获取当前页面指定资源名称的路径
function getJsPath(name){
    var js=document.scripts;
    var jsPath;
    for(var i=js.length;i>0;i--){
        if(js[i-1].src.indexOf(name)>-1){
            jsPath=js[i-1].src.substring(0,js[i-1].src.lastIndexOf("/"));
        }
    }
    return jsPath;
}

//去掉url地址的参数，获取到不带参数的url
function getNoParamUrl(url){
    if (url==null){return null;}
    if (url.indexOf("?")==-1){
        return url;
    }else {
        return url.substring(0,url.indexOf("?"));
    }
}


/**
 * 将空内容替换为空字符串，同时格式化时间格式和小数
 * @param ob
 * @param str   为空时返回的字符
 * @param point   小数数值要保留的位数
 * @returns {*}
 * @private
 */
function nvl_(ob,str,point){
    if (ob==null||ob=='null'||ob=='undefined'){
        if (str==null){
            return "";
        }else {
            return str;
        }
    }

    try {
        var dType = strIsDateOrTime(ob);
        if (dType == 'idatetime' || dType == 'date') {
            ob=ob.replace(/[-]/g,"/");
            return new Date(ob).format("yyyy-MM-dd");
        }

        if (/^[+-]?[1-9]?[0-9]*\.[0-9]*$/.test(ob)){
            point=(point==null?3:point);
            return ob.toFixed(point);
        }

    } catch (e) {
        console.log(e)
    }
    return ob;
}

/**
 * 火狐下不支持横线格式的日期 ob=ob.replace(/[-]/g,"/");
 * @param format
 * @returns {*}
 */
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };
    if(/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for(var k in o) {
        if(new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

/**判断是否是日期时间格式返回值为itime,idate,idatetime,none,date*/
function strIsDateOrTime(str){
    if(str==null || str=='' || str=='null' || str=='undefined'){return "none";}
    if($.type(str)=='date'){return "date"}
    if($.type(str)!='string'){return "none"}

    //首先判断是否是完整的日期时间
    var reg = date_time_Regx;
    var r = str.match(reg);
    if(r==null){}else{
        var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
        if (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]){
            return "idatetime";
        }};

    /**第二判断是否是日期格式*/
    r=null;
    d=null;
    r=str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
    if(r==null){}else{
        d= new Date(r[1], r[3]-1, r[4]);
        if((d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4])){
            return "idate";
        }
    }
    /**判断是否是时间格式*/
    r=null;
    d=null;
    r=str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/);
    if(r==null){}else{
        if (r[1]>24 || r[3]>60 || r[4]>60){return "none";}else{
            return "itime";
        }
    }
    return "none";
}

//重写toFixed四舍五入方法
Number.prototype.toFixed = function (d) {
    var s = this + "";
    if(!d)d = 0;
    if(s.indexOf(".") == -1)s += ".";
    s += new Array(d + 1).join("0");
    if(new RegExp("^(-|\\+)?(\\d+(\\.\\d{0," + (d + 1) + "})?)\\d*$").test(s)) {
        var s = "0" + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true;
        if(a == d + 2) {
            a = s.match(/\d/g);
            if(parseInt(a[a.length - 1]) > 4) {
                for(var i = a.length - 2; i >= 0; i--) {
                    a[i] = parseInt(a[i]) + 1;
                    if(a[i] == 10) {
                        a[i] = 0;
                        b = i != 1;
                    } else break;
                }
            }
            s = a.join("").replace(new RegExp("(\\d+)(\\d{" + d + "})\\d$"), "$1.$2");
        }
        if(b)s = s.substr(1);
        return (pm + s).replace(/\.$/, "");
    }
    return this + "";
};


//判断字符串是否为空
function isEmpty(str){
    if (str==null||str==''){
        return true;
    }else {
        return false;
    }
}

/**
 * Map类
 * 实现了类似于Java语言中的Map接口的常用方法
 */
function Map(){

    //key集
    this.keys = new Array();

    //value集
    this.values = new Array();

    //添加key-value进Map
    this.put = function(key, value){
        if(key == null || key == undefined)
            return;
        var length = this.size();
        for(var i = 0 ; i < length ; i ++ ) {
            //如果keys数组中有相同的记录，则不保存重复记录
            if(this.keys[i] == key)
                return;
        }
        this.keys.push(key);
        this.values.push(value);
    };

    //获取指定key的value
    this.get = function(key){
        var length = this.size();
        for(var i = 0 ; i < length ; i ++ ) {
            if(this.keys[i] == key) {
                return this.values[i];
            } else {
                continue;
            }
            return null;
        }
    };

    //移除指定key所对应的map
    this.remove = function(key) {
        var length = this.size();
        for(var i = 0 ; i < length ; i ++ ) {
            if(this.keys[i] == key) {
                while(i < length - 1) {
                    this.keys[i] = this.keys[i+1];
                    this.values[i] = this.values[i+1];
                    i ++ ;
                }
                //处理最后一个元素
                this.keys.pop();
                this.values.pop();
                break;
            }
        }
    };

    //是否包含指定的key
    this.containsKey = function(key) {
        var length = this.size();
        for(var i = 0 ; i < length ; i ++ ) {
            if(this.keys[i] == key) {
                return true;
            }
        }
        return false;
    };

    //是否包含指定的value
    this.containsValue = function(value) {
        var length = this.size();
        for(var i = 0 ; i < length ; i ++ ) {
            if(this.values[i] == value) {
                return true;
            }
        }
        return false;
    };

    //包含记录总数
    this.size = function() {
        return this.keys.length;
    };

    //是否为空
    this.isEmpty = function() {
        return this.size() == 0 ? true : false;
    };

    //清空Map
    this.clear = function() {
        this.keys = new Array();
        this.values = new Array();
    };

    //将map转成json字符串，格式：{"key1":"value","key2":"value2"}
    this.toString = function() {
        var length = this.size();
        var str = "{";
        for(var i = 0 ; i < length ; i ++ ) {
            str = str +"\""+ this.keys[i] + "\":\"" + this.values[i]+"\"";
            if(i != length-1)
                str += ",";
        }
        str +="}";
        return str;
    };
}

var uploadDialog_;
function openUploadDialog(data){
    var url=p_path+"/public/upload/upLoadPage.html";
    var data_={};
    var title=nvl_(data.title);
    $.extend(data_,data);
    uploadDialog_=$.dialog({
        title:title,
      //  id : "dig" + (new Date()).getTime(),
        content:"url:"+url,
        width : 700,
        height : 500,
        max:false,
        min:false,
        lock : true,
        data:data_,
        zIndex: 9999
    });
}

//为自定义的复选框添加事件和样式
function initCkBox(obj){
    $(".table-ck .check-box i").die();
    obj.off().on('click',"th .table-ck .check-box i", function () {
        $("th .table-ck .check-box i",obj).toggleClass('active');
        if ($(this).hasClass('active')){
            $("td .table-ck .check-box i",obj).addClass("active");
        }else {
            $("td .table-ck .check-box i",obj).removeClass("active");
        }
    });
    obj.on('click',"td .table-ck .check-box i", function () {
        $(this).toggleClass('active');
        var tdCKNUM=$("td .table-ck .check-box i",obj).length;
        var ckdNUM=$("td .table-ck .check-box  .active",obj).length
        if (tdCKNUM==ckdNUM){
            $("th .table-ck .check-box i",obj).addClass("active");
        }else {
            $("th .table-ck .check-box i",obj).removeClass("active");
        }
    });
}

var myTableOpt_={
    getStatus:function(state,funName,id){
        var hangClass = "active" == state ? "on-off active":"on-off";
        var html = "<li style='list-style-type:none;' class='s20-0-8'><em class='"+hangClass+"' onclick="+funName+"></em></li>";
        return html;
    },
    getCheckBox:function(id,data2,fun,ischecked){
        var hangClass = null == id ? "sw5-1" : "w5";
        var html = "<li style='list-style-type:none;' class='"+hangClass+"'><span class='table-ck'><span class='check-box selected' >" ;
        if (id!=null){
            html+="<i class='"+nvl_(ischecked)+"' datav='"+id+"' otherdatav='"+nvl_(data2)+"' onclick="+nvl_(fun)+"></i>";
            html+= "<input name='ckInput_' type='hidden' value='"+id+"'/>" ;
        }else {
            html+="<i></i>";
        }

        html+=   "</span></span></li>";
        return html;
    },
    getCheckBoxValues:function(obj){
        var dataArr = new Array();
        $(".table-ck .check-box .active",obj).each(function(i,d){
            var v=$(d).attr("datav");
            if (v!=null){
                dataArr.push(v);
            }

        });

        return dataArr;
    }

};


function initMyForm(id){
    $("input,textarea",$("#"+id)).val('').html("");
}


function backgroundExport(url){
    $("#hideExpIframe_").remove();
    $("<iframe id='hideExpIframe_' style='display: none' src='"+url+"' />").appendTo("body");
}

var backgroundExportByForm={
    "initForm":function(url){
        var form=$("#back_form");
        if (form.length==0){
            $("<form id='back_form' action="+url+" method=post target=hideExpIframe_ style=display:none></form>").appendTo("body");
        }
    },
    "initIframe":function(){
        var fm=$("#hideExpIframe_").length;
        if (fm==0){
            $("<iframe name='hideExpIframe_' id='hideExpIframe_' style='display: none' src='#' />").appendTo("body");
        }
    },
    "putDomToForm":function(dom,url){
        backgroundExportByForm.initForm(url);
        $("*[name="+($(dom).attr("name"))+"]",$("#back_form")).remove();
        //alert(document.getElementById("back_form").outerHTML)
        $("#back_form").append(dom);
    },
    "submit":function(){
        backgroundExportByForm.initIframe();
        $("#back_form").submit();
    }
}



